<template>
  <div>
    <headNav :title="title" ></headNav>
    <!-- 设置亲情号码模块 -->
    <div class="flexHeight bigDivCss" v-if="title == '设置亲情号码'" >
      <span class="titleCss" >最多可设置4个亲情号码，并设置其中一个为SOS号码</span>
      <div class="flexHeight" style="margin-top: 0.2rem;" v-for="(val, index) in phoneSOS" :key="index" >
        <div class="flexAlign" style="font-size: 0.3rem;" >
          <span>号码{{val.id}}：</span>
          <relation v-model="val.nickName" :list="relationList"></relation>
          <input type="text" v-model="val.phone" @input="inputChange(val)" placeholder="请输入号码" />
        </div>
        <div class="flexAlign bottomCss" :class="{bottomCss1: val.state == 4}" >
          <img src="@/assets/img/my/available.png" mode="" v-if="val.state == 1" >
          <img src="@/assets/img/my/availableNo.png" mode="" v-if="val.state == 2 || val.state == 0" style="width: 1.2rem;" >
          <span>是否设置为sos号码：</span>
          <x-switch title="" :value-map="[false, true]" v-model="val.sos" @click.native="sosChange(val.id)" ></x-switch>
        </div>
      </div>
      <div class="flexCenter buttonDiv" >
        <button type="default" @click="preservationClick" >保存</button>
      </div>
    </div>
    <!-- 绑定学生模块 -->
    <div class="flexHeight headNameCss" v-if="title == '绑定学生' || title == '编辑绑定学生'" >
      <div class="flexAlign" >
        <span>卡号：</span>
        <input type="text" v-model="certificateNum" placeholder="请输入学生证卡号" />
        <img class="code-img" @click="scanQRCode" src="@/assets/img/my/code.png" alt="">
      </div>
      <button type="default" @click="determineBinding" >确定</button>
    </div>
  </div>
</template>

<script>
import headNav from '@/components/headNav/headNav.vue'
import { mapActions, mapState, mapGetters, mapMutations } from 'vuex'
import { XSwitch  } from 'vux'
import { postbindingDeviceApi, getFamilyNumApi, postFamilyNumApi, postFamilyNumSOSApi, getDictionariesApi } from '@/api/myNewApi'

import relation from './relation'
export default {
  components: {
    headNav,
    XSwitch,
    relation
    
  },
  computed: {
    ...mapState({
      studentId: state => state.user.studentId,
      roleCode: state => state.user.roleCode
    })
  },
  data () {
    return {
      studentVal: '' ,  // 选择的学生信息
      certificateNum: '',  // 输入的学生证号
      title: '',  // 是什么功能跳转过来
      phoneSOS: [
        {id: 1, nickName: '', phone: '', sos: false, state: 4 },
        {id: 2, nickName: '', phone: '', sos: false, state: 4 },
        {id: 3, nickName: '', phone: '', sos: false, state: 4 },
        {id: 4, nickName: '', phone: '', sos: false, state: 4 },
      ],
      relationList: []
    }
  },
  methods: {
    // 输入框输入动作时触发事件
    inputChange(e) {
      e.state = 4
    },
    // 是否设置亲情号码按钮触发事件
    sosChange (e) {
      for (let val of this.phoneSOS) {
        if (val.id == e) {
          this.$set(val, 'sos', true)
        } else {
          this.$set(val, 'sos', false)
        }
      }
      console.log(this.phoneSOS)
    },
    // 保存亲情号码按钮
    async preservationClick () {
      let iphone = false
      for (let i of this.phoneSOS) {
        if (i.phone) {
          iphone = true
        }
      }
      if (!iphone) {
        this.$vux.toast.text('至少填写一个亲情号码', 'middle')
        return
      }


      console.log(this.phoneSOS)
      var patrn = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
      for (let i of this.phoneSOS) {
        if (i.sos && !i.phone) {
          this.$vux.toast.text('设置的sos号码为空', 'middle')
          return
        }

        if (i.phone) {
          if(!patrn.exec(i.phone)){
            this.$vux.toast.text('手机号码格式有误，请重填', 'middle')
            return
          }
        }
      }

      this.$vux.confirm.show({
          title: '提示',
          content: '是否确定设置亲情号码？',
          onConfirm : async () => {



            let list = []
            let sosPhone = []
            for (let val of this.phoneSOS) {
              if (val.phone) {
                list.push({phone: val.phone, nickName: val.nickName})
              }
              if (val.sos) {
                sosPhone.push({phone: val.phone})
              }
            }
            let params = {
              studentId: this.studentVal.studentId,
              familyPhones: list
            }
            
            await postFamilyNumApi(params)
            let paramss = {
              studentId: this.studentVal.studentId,
              sosPhones: sosPhone
            }
            await postFamilyNumSOSApi(paramss)
            this.$router.push('studentIDCard')
           
            
             this.$vux.alert.show({
                title: '提示',
                content: '设置成功，号码需审核，建议24小时后拨打。',
             })

          },
          onCancel () {
          }
      })

    },
    // 请求亲情号码封装
    async packFamilyNum () {
      let res = await getFamilyNumApi(this.studentVal.studentId)
      
      for (let i = 0; i < res.phoneDetails.length; i++) {
        
            this.phoneSOS[i].nickName = res.phoneDetails[i].nickName
            this.phoneSOS[i].phone = res.phoneDetails[i].phone
            this.phoneSOS[i].sos = res.phoneDetails[i].isSetSOS
            this.phoneSOS[i].state = res.phoneDetails[i].state
       
      }
     
      console.log(this.phoneSOS)
    
      
    },
    // 绑定学生证确定按钮触发事件
    async determineBinding () {
      if (!this.certificateNum) {
        this.$vux.toast.text('请输入学生证号', 'middle')
        return
      }

      var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]")
    　if (pattern.test(this.certificateNum)){
         this.$vux.toast.text('严禁输入特殊字符', 'middle')
    　　　return
    　}

      let re = /[A-Za-z]+/;
      if (/.*[\u4e00-\u9fa5]+.*$/.test(this.certificateNum) || this.certificateNum.search(re) >= 0) {
        this.$vux.toast.text('不能含有汉字或者英文', 'middle')
        return
      }


      let lengths = this.certificateNum.length
      if (lengths != 15) {
        this.$vux.toast.text('学生证号长度只允许15位数', 'middle')
        return;
      }

      this.$vux.confirm.show({
        title: '提示',
        content: '是否确定执行该操作？',
        onConfirm : async () => {
          let params = {
            studentId: this.studentVal.studentId,
            deviceNo: this.certificateNum
          }
          await postbindingDeviceApi(params)
          this.$vux.toast.text('绑定成功', 'middle')
          this.$router.push('studentIDCard')
        },
        onCancel () {
        }
      })

    },

    scanQRCode(){
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: (res) => {
          var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
          this.certificateNum = result.split(',')[1]
        }
      });
    },

     async getRelationList(){
           
            this.relationList = await getDictionariesApi({
                typeCode: 'FamilyRelation'
            })

            // description: null
            // orderNum: 1
            // status: true
            // typeCode: "IdCardType"
            // valCode: "ResidentIdCard"
            // valName: "居民身份证"
            
        }
  },

  
  async mounted() {
    await this.getRelationList()

    this.title = localStorage.studentIDCard
    this.studentVal = JSON.parse(localStorage.localBindingDevice)
    if (this.title == '设置亲情号码') {
      this.packFamilyNum()
    }
    if (this.title == '编辑绑定学生') {
      this.certificateNum = this.studentVal.deviceNo
    }
  }
}
</script>

<style lang="less" scoped >
.headNameCss {
 .flexHeight;
 justify-content: center;
 align-items: center;
 div {
   width: 6.2rem;
   height: 1rem;
   margin: 0.3rem 0 0 0.2rem;
   border-bottom: 1px solid #bdbdbd;
   font-size: 0.3rem;
 }
 input {
   width: 4rem;
   height: 0.6rem;
   margin-left: 0.2rem;
   
   border-radius: 0.2rem;
   font-size: 0.3rem;
   background: #f4f4f4;
 }
 button {
   width: 5rem;
   height: 0.7rem;
   color: #FFF;
   background: #128fef;
   border-radius: 0.3rem;
   border: 0;
   font-size: 0.3rem;
   margin-top: 0.5rem;
 }
}

.buttonDiv {
  width: 100%;
  margin-top: 0.3rem;
  button {
    width: 5.6rem;
    height: 0.85rem;
    background: #128FEF;
    color: #FFF;
    font-size: 0.32rem;
    border-radius: 0.42rem;
    border: 0;
  }
}

.bigDivCss {
  justify-content: center;
  align-items: center;
  .titleCss {
    color: #666;
    font-size: 0.24rem;
    margin: 0.3rem 0;
  }
  input {
    width: 3.5rem;
    height: 0.85rem;
    border-radius: 0.1rem;
    font-size: 0.3rem;
    padding-left: 0.2rem;
  }
  .bottomCss {
    font-size: 0.28rem;
    color: #999999;
    margin-left: 0.5rem;
    img {
      width: 1rem;
      height: 0.5rem;
    }
  }
}

.bottomCss1 {
  margin-left:1.7rem!important;
}

.flexCenter {
  display: flex;
  align-items: center;
  justify-content: center;
}

.flexHeight {
  display: flex;
  flex-direction: column;
}

.flexAlign {
  display: flex;
  align-items: center;
  position: relative;
}

.flexEdge {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.code-img{
  width: 0.5rem; height: 0.4rem;
  position: absolute; right: 0; top: 50%;
    transform: translateY(-50%);
}
</style>
